package pers.qianyu.month_202101.date_20210123;

/**
 * 34. 在排序数组中查找元素的第一个和最后一个位置
 * https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
 * - 使用y总的模板解法
 * - 参考视频：https://www.bilibili.com/video/BV1Ft41157zW
 *
 * @author mizzle rain
 * @date 2021-01-23 16:32
 */
public class SearchRange2 {
    public int[] searchRange(int[] nums, int target) {
        int len = nums.length;
        if (len == 0) return new int[]{-1, -1};
        int left = 0, right = len - 1;
        while (left < right) {
            int mid = (left + right) >> 1;
            if (nums[mid] >= target) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        if (nums[left] != target) return new int[]{-1, -1};
        int[] res = {left, -1};
        left = 0;
        right = len - 1;
        while (left < right) {
            int mid = (left + right + 1) >> 1;
            if (nums[mid] <= target) {
                left = mid;
            } else {
                right = mid - 1;
            }
        }
        res[1] = left;
        return res;
    }
}
